<?php

namespace App\logic\Api;

use Illuminate\Http\Request;

class AiLogic
{
    //考虑流式输出
    public static function openAI($content)
    {
        $params = [
            'model' => 'gpt-3.5-turbo-16k',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => $content
                ]
            ],
            'temperature' => 0.7,
            'stream' => true,
            'top_p' => 1,
            'frequency_penalty' => 0,
            'presence_penalty' => 0,
            'n' => 1,
            'max_tokens' => 2048
        ];


        $res = self::urlRequest($params);
        dd($res);
//        dump($res);
        return ['message' => $res['message']];

    }

    public static function urlRequest($params)
    {
        // 初始化 cURL
        $message = '';
        $curl = curl_init();
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        // 设置 cURL 选项
        curl_setopt($curl, CURLOPT_URL, 'https://api.chatgptid.net/v1/chat/completions');
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
            "Authorization: Bearer sk-RtqA2FBnX127NnaaB73e15A4AbFa4aE88850EfFdB760DaAc",
        ));
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 将响应保存到变量中，而不是直接输出

        // 执行cURL请求并获取响应
        $response = curl_exec($curl);

        // 检查是否有错误发生
        if (curl_errno($curl)) {
            echo 'cURL error: ' . curl_error($curl);
        }

        // 关闭cURL会话
        curl_close($curl);

        // 处理响应
        return $response;
    }

    public static function postRequest($url, $data)
    {
        // 初始化cURL会话
        $ch = curl_init($url);
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // 使用POST请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // 设置POST数据为JSON格式
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json', // 设置请求头为JSON格式
            'Content-Length: ' . strlen(json_encode($data)) // 设置请求体长度
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应保存到变量中，而不是直接输出

        // 执行cURL请求并获取响应
        $response = curl_exec($ch);

        // 检查是否有错误发生
        if (curl_errno($ch)) {
            echo 'cURL error: ' . curl_error($ch);
        }

        // 关闭cURL会话
        curl_close($ch);

        // 处理响应
        return $response;
    }

    public static function search($data)
    {
        $query = $data['keyword'];

        // 发送 POST 请求到 YouTube 搜索接口
        $response = self::postRequest('https://www.youtube.com/youtubei/v1/search', [
            'context' => [
                'client' => [
                    'hl' => 'zh-CN',
                    'gl' => 'KR',
                    'remoteHost' => '92.38.134.89',
                    'deviceMake' => 'Apple',
                    'deviceModel' => '',
                    'userAgent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36,gzip(gfe)',
                    'clientName' => 'WEB',
                    'clientVersion' => '2.20230309.08.00',
                    'osName' => 'Macintosh',
                    'osVersion' => '10_15_7',
                    'originalUrl' => 'https://www.youtube.com/results?search_query=' . urlencode($query),
                    'platform' => 'DESKTOP',
                    'clientFormFactor' => 'UNKNOWN_FORM_FACTOR',
                    'browserName' => 'Chrome',
                    'browserVersion' => '92.0.4515.159',
                    'acceptHeader' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                    'screenWidthPoints' => 1302,
                    'screenHeightPoints' => 2000,
                    'screenPixelDensity' => 1,
                    'screenDensityFloat' => 1,
                    'utcOffsetMinutes' => 480,
                    'userInterfaceTheme' => 'USER_INTERFACE_THEME_LIGHT',
                    'memoryTotalKbytes' => '8000000',
                    'timeZone' => 'Asia/Shanghai',
                ],
                'user' => [
                    'lockedSafetyMode' => false,
                ],
                'request' => [
                    'useSsl' => true,
                ],
            ],
            'query' => $query,
        ]);

        $searchResult = json_decode($response, true);

        // 处理搜索结果
        $videoData = self::searchResultHandler($searchResult);
        $content = self::videoDetail($videoData[0]['id']);
        $language = $data['language'];

        //查对应的模版
        $template = $data['template'];


        $template = str_replace('{{language}}', $language, $template);
        $template = str_replace('{{content}}', $content, $template);

        self::openAI($template);

        // 返回视频数据
        return response()->json($videoData);
    }

    public static function videoDetail($videoId)
    {
        $url = 'https://www.youtube.com/watch?v=' . $videoId;

        $headers = [
            'authority: www.youtube.com',
            'pragma: no-cache',
            'cache-control: no-cache',
            'sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
            'sec-ch-ua-mobile: ?0',
            'sec-ch-ua-full-version: "92.0.4515.159"',
            'sec-ch-ua-arch: "x86"',
            'sec-ch-ua-platform: "macOS"',
            'sec-ch-ua-platform-version: "10_15_7"',
            'sec-ch-ua-model: ""',
            'upgrade-insecure-requests: 1',
            'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
            'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'service-worker-navigation-preload: true',
            'sec-fetch-site: same-origin',
            'sec-fetch-mode: navigate',
            'sec-fetch-user: ?1',
            'sec-fetch-dest: document',
            'accept-language: zh-CN,zh;q=0.9,en;q=0.8',
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);

//        dd($response);

        // 处理视频详情页面 HTML，获取字幕链接
        $captionUrl = self::videoDetailResultHandler($response);
        $content = self::videoCaption($captionUrl);
        $content = substr($content, 100, 1000);
        return $content;

        // 返回字幕链接
    }

    public static function videoCaption($url)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
        }
        curl_close($ch);

        // 解析XML内容并提取文本
        $xml = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA);
        $captions = [];

        foreach ($xml->text as $text) {
            // 将 SimpleXMLElement 转换为字符串，并处理 HTML 实体编码
            $captions[] = html_entity_decode((string)$text, ENT_QUOTES | ENT_XML1, 'UTF-8');
        }

        // 将所有文本内容连接成一个字符串
        $captionText = implode(' ', $captions);

        return $captionText;
    }

    private static function searchResultHandler($searchResult)
    {
        $videoData = [];

        $videoRenderers = self::getVideoRenderers($searchResult);

        foreach ($videoRenderers as $videoRenderer) {
            $video = $videoRenderer['videoRenderer'];
            if (!$video || !isset($video['title']['runs'][0]['text'])) {
                continue;
            }
            $videoData[] = [
                'id' => $video['videoId'],
                'title' => $video['title']['runs'][0]['text'],
            ];
        }

        return $videoData;
    }

    private static function videoDetailResultHandler($videoHtml)
    {
        $captionsJson = self::extractCaptionsJson($videoHtml);

        if (!$captionsJson) {
            return null; // 没有找到字幕链接
        }

        $captionTracks = $captionsJson['playerCaptionsTracklistRenderer']['captionTracks'];

        foreach ($captionTracks as $caption) {
            if ($caption['languageCode'] === 'en') {
                return $caption['baseUrl'];
            }
        }

        return null; // 没有找到英文字幕链接
    }

    private static function extractCaptionsJson($videoHtml)
    {
        // 正则表达式提取包含字幕的 JSON 数据
        preg_match('/"captions":({.*?}),"videoDetails"/s', $videoHtml, $matches);

        if (count($matches) < 2) {
            return null;
        }

        return json_decode($matches[1], true);
    }

    private static function getVideoRenderers($obj)
    {
        $videoRenderers = [];

        self::traverse($obj, function ($item) use (&$videoRenderers) {
            if (isset($item['videoRenderer'])) {
                $videoRenderers[] = $item;
            }
        });

        return $videoRenderers;
    }

    private static function traverse($obj, callable $callback)
    {
        foreach ($obj as $key => $value) {
            $callback($value);

            if (is_array($value) || is_object($value)) {
                self::traverse($value, $callback);
            }
        }
    }
}
